package ils.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 * Created with IntelliJ IDEA.
 * User: rejeevd
 * Date: 20/09/12
 * Time: 22:52
 * To change this template use File | Settings | File Templates.
 */
public class HibernateSessionManager
{
    public static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    public static final ThreadLocal<String> transactionKey = new ThreadLocal<String>();

    public HibernateSession getSession()
    {
        Session session = sessionFactory.getCurrentSession();
        if(!session.getTransaction().isActive())
        {
            String key = Util.randomString(20);
            transactionKey.set(key);
            session.beginTransaction();
            return new HibernateSession(key);
        }
        return null;
    }

    public void complete(String txnKey)
    {
        if(transactionKey.get().equals(txnKey))
        {
            sessionFactory.getCurrentSession().getTransaction().commit();
            transactionKey.remove();
        }
    }

    public void rollback()
    {
        sessionFactory.getCurrentSession().getTransaction().rollback();
    }
}
